package com.xmh.reptile.util;

import cn.hutool.core.io.FileUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import static com.alibaba.fastjson.JSONObject.parseObject;
import static com.alibaba.fastjson.JSONObject.toJSONString;

public class RedisMockUtil {

    private static final String charsetName = "UTF-8";
    private static final File file = new File("src/main/resources/redis/redis.json");
    private static final Map<String, Object> CACHE_MAP = getMap();

    public static void set(String Key, Object value) {
        CACHE_MAP.put(Key, value);
        FileUtil.writeString(toJSONString(CACHE_MAP), file, charsetName);
    }

    private static Map<String, Object> getMap() {
        String json = FileUtil.readString(file, charsetName);
        return StringUtils.isEmpty(json) ? new HashMap<>() : parseObject(json, Map.class);
    }

    public static Object get(String key) {
        return CACHE_MAP.get(key);
    }
}
